const Koa = require('koa')
const path = require('path')
const { koaBody } = require('koa-body')
const { DataTypes, Sequelize } = require('sequelize')
const { v4: uuidv4 } = require('uuid')
const routes = require('./routes')
const koaStatic = require('koa-static')

const app = new Koa()
app.use(koaBody())

app.use(koaStatic(path.join(__dirname, '../client/build')))

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*')
  ctx.set('Access-Control-Allow-Headers', 'Content-Type')
  ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
  if (ctx.method === 'OPTIONS') {
    ctx.body = 200
  } else {
    await next()
  }
})

const db = new Sequelize({
  dialect: 'sqlite',
  storage: './db.sqlite',
  logging: false
})

const User = db.define('User', {
  id: {
    type: DataTypes.STRING,
    defaultValue: uuidv4(),
    primaryKey: true
  },
  isOpen: DataTypes.BOOLEAN,
  theme: DataTypes.STRING,
  codeAll: DataTypes.JSON,
  password: DataTypes.STRING,
  title: DataTypes.STRING,
  label: DataTypes.JSON,
  currentTime: DataTypes.STRING,
  endTime: DataTypes.STRING,
  mdContent: DataTypes.STRING,
  codeUrl: DataTypes.STRING
})

User.sync()

app.use(routes.routes()).use(routes.allowedMethods())

// 中间件函数处理 /submit 请求
const handleSubmit = async (ctx, next) => {
  if (ctx.url === '/submit' && ctx.method === 'POST') {
    const body = ctx.request.body
    try {
      await User.create(body)
      ctx.status = 201
      ctx.body = { message: 'User created successfully' }
    } catch (error) {
      ctx.status = 500
      ctx.body = { error: error.message }
    }
  } else {
    await next()
  }
}

// 中间件函数处理 /delete 请求
const handleDelete = async (ctx, next) => {
  if (ctx.url === '/delete' && ctx.method === 'POST') {
    const { id } = ctx.request.body
    try {
      await User.destroy({ where: { id } })
      ctx.status = 200
      ctx.body = { message: 'User deleted successfully' }
    } catch (error) {
      ctx.status = 500
      ctx.body = { error: error.message }
    }
  } else {
    await next()
  }
}

// 中间件函数处理 /update 请求
const handleUpdate = async (ctx, next) => {
  if (ctx.url === '/update' && ctx.method === 'POST') {
    const body = ctx.request.body
    const { id, ...userData } = body

    try {
      const [updatedRows] = await User.update(userData, { where: { id } })
      // updatedRows是记录多少项被更新过
      if (updatedRows > 0) {
        ctx.status = 200
        ctx.body = { message: 'User updated successfully' }
      } else {
        ctx.body = { message: 'User not found' }
      }
    } catch (error) {
      ctx.status = 500
      ctx.body = { error: error.message }
    }
  } else {
    await next()
  }
}

// 中间件函数处理 /get 请求，请求全部的User表数据
const handleGet = async (ctx, next) => {
  if (ctx.url === '/get' && ctx.method === 'GET') {
    try {
      const users = await User.findAll()
      if (users.length > 0) {
        ctx.status = 200
        ctx.body = users
      }
    } catch (error) {
      ctx.status = 500
      ctx.body = { error: error.message }
    }
  } else {
    await next()
  }
}

// 注册中间件函数
app.use(handleSubmit)
app.use(handleDelete)
app.use(handleUpdate)
app.use(handleGet)

app.listen(3001, () => {
  console.log('server start at port 3001')
})
